package com.ai.dtcore.service.impl;

import java.text.DecimalFormat;
import java.util.Date;

import org.apache.commons.lang3.RandomUtils;

import com.ai.dtcore.dao.impl.BaseDaoImpl;
import com.ai.dtcore.service.ICacheService;
import com.ai.dtcore.util.DateUtil;
import com.ai.dtcore.util.MyOwnRuntimeException;
import com.ai.dtcore.util.StringUtil;
import com.ai.dtcore.util.DateUtil.DATE_PATTERN;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;

/**
 */
public class BaseServiceImpl {
	private Logger logger = LoggerFactory.getServiceLog(BaseServiceImpl.class);
	private BaseDaoImpl baseDao;// 用户中心操作的dao
	// private BaseContactDaoImpl baseContactDao;// 接触中心操作的dao
	private ICacheService cacheService;

	public BaseDaoImpl getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(BaseDaoImpl baseDao) {
		this.baseDao = baseDao;
	}

	public ICacheService getCacheService() {
		return cacheService;
	}

	public void setCacheService(ICacheService cacheService) {
		this.cacheService = cacheService;
	}

	// public BaseContactDaoImpl getBaseContactDao() {
	// return baseContactDao;
	// }
	//
	// public void setBaseContactDao(BaseContactDaoImpl baseContactDao) {
	// this.baseContactDao = baseContactDao;
	// }

	/**
	 * 主键生成策略
	 * 
	 * @param tableName
	 *            需要获取主键的表名
	 */
	public String getSequence(String tableName) throws MyOwnRuntimeException {
		if (StringUtil.isEmpty(tableName)) {
			throw new MyOwnRuntimeException("获取主键时前缀不能为空!建议传入表名");
		}
		String redisKey = "REDIS_TBL_" + tableName;
		String id = null;
		try {
			logger.info("开始获取主键 ", "key=" + redisKey);
			id = DateUtil.date2String(new Date(), DATE_PATTERN.YYYYMMDDHHMMSSSSS) + ""
					+ new DecimalFormat("#000").format(getCacheService().incr(redisKey));
			logger.info("获取主键成功", "id=" + id);
		} catch (Exception e) {
			logger.error("使用redis获取主键失败，开始使用随机数", "key=" + redisKey, e);
			id = DateUtil.date2String(new Date(), DATE_PATTERN.YYYYMMDDHHMMSSSSS) + ""
					+ new DecimalFormat("#000").format(RandomUtils.nextInt(1, 1000));
			logger.error("NOT ERROR! 主键获取成功", "key=" + redisKey + ",id=" + id);
		}
		return id;
	}
}